//
//  CLForgetPWViewController.m
//  CareLink
//
//  Created by w on 16/8/18.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLForgetPWViewController.h"
#import "CLNewPWViewController.h"
#import "CLAEViewController.h"
#import "SVProgressHUD.h"
#import <SMS_SDK/SMSSDK.h>
#import "CLNewPWViewController.h"

@interface CLForgetPWViewController ()
{
    //视图
    UIView *bgView;
    //UITextField *phone;
    UINavigationBar *customNavigationBar;
    //添加的按钮
    UIButton *yyButton;
    //手机号
    UITextField *phone2;
    //验证码内容
    UITextField *code2;


    }
    //记录发送短信的电话号码字符串
    @property (nonatomic, copy) NSString *keyStr;
    @property(nonatomic, copy) NSString *oUserPhoneNum;
    @property(assign, nonatomic) NSInteger timeCount;
    @property(strong, nonatomic) NSTimer *timer;
    //验证码
    @property(copy, nonatomic) NSString *smsId;
    //@property (nonatomic, strong) UITextField *phone2;

@end

/**
 *  找回密码1/2
 */
@implementation CLForgetPWViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //隐藏navBar
    self.navigationController.navigationBarHidden = NO;
    self.title=@"找回密码";
    
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(clickaddBtn)];
    [addBtn setImage:[UIImage imageNamed:@"goback_back_orange_on"]];
    [addBtn setImageInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
    addBtn.tintColor = [UIColor colorWithRed:8/255.0 green:65/255.0 blue:130/255.0 alpha:0.8];
    [self.navigationItem setLeftBarButtonItem:addBtn];
    
    
    [self createTextFields];
}
-(void)clickaddBtn
{
    [self.navigationController popViewControllerAnimated:YES];
    //[self.navigationController pushViewController:[[MMZCViewController alloc]init] animated:YES];
}
-(void)createTextFields
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 75, self.view.frame.size.width-90, 30)];
    label.text = @"请输入您的手机号码";
    label.textColor = [UIColor grayColor];
    label.textAlignment = UITextAlignmentLeft;
    label.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:label];
    
    CGRect frame = [UIScreen mainScreen].bounds;
    bgView = [[UIView alloc]initWithFrame:CGRectMake(10, 110, frame.size.width-20, 100)];
    bgView.layer.cornerRadius=3.0;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
   phone2 = [self createTextFielfFrame:CGRectMake(100, 10, 200, 30) font:[UIFont systemFontOfSize:14] placeholder:@"11位手机号"];
    phone2.clearButtonMode = UITextFieldViewModeWhileEditing;
    phone2.keyboardType = UIKeyboardTypeNumberPad;
    //phone.text=@"18701646234";
    
    code2 = [self createTextFielfFrame:CGRectMake(100, 60, 90, 30) font:[UIFont systemFontOfSize:14]  placeholder:@"4位数字" ];
    code2.clearButtonMode = UITextFieldViewModeWhileEditing;
    //code.text=@"123456";
    //密文样式
    code2.secureTextEntry = YES;
    code2.keyboardType = UIKeyboardTypeNumberPad;
    
    
//    UILabel *phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 12, 50, 25)];
//    phonelabel.text = @"手机号";
//    phonelabel.textColor = [UIColor blackColor];
//    phonelabel.textAlignment = UITextAlignmentLeft;
//    phonelabel.font = [UIFont systemFontOfSize:14];
//    
//    UILabel *codelabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 62, 50, 25)];
//    codelabel.text = @"验证码";
//    codelabel.textColor = [UIColor blackColor];
//    codelabel.textAlignment = UITextAlignmentLeft;
//    codelabel.font = [UIFont systemFontOfSize:14];
//
    UIImageView* userImageView1 = [self createImageViewFrame:CGRectMake(29, 10, 16, 20) imageName:@"注册-手机号" color:nil];
    UIImageView* pwdImageView2 = [self createImageViewFrame:CGRectMake(24, 60, 25, 25) imageName:@"mm_normal" color:nil];
    
   yyButton = [[UIButton alloc]initWithFrame:CGRectMake(bgView.frame.size.width-100-20, 62, 100, 30)];
    //yzButton.layer.cornerRadius = 3.0f;
    //yzButton.backgroundColor = [UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    [yyButton  setTitle:@"获取验证码" forState:UIControlStateNormal];
    [yyButton setTitleColor:[UIColor colorWithRed:8/255.0 green:65/255.0 blue:130/255.0 alpha:0.8] forState:UIControlStateNormal];
    yyButton .font = [UIFont systemFontOfSize:13];
    [yyButton  addTarget:self action:@selector(getValidCode:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:yyButton];
    
    UIImageView *line1 = [self createImageViewFrame:CGRectMake(20, 50, bgView.frame.size.width-40, 1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    UIButton *landBtn = [self createButtonFrame:CGRectMake(10, bgView.frame.size.height+bgView.frame.origin.y+20,self.view.frame.size.width-20, 37) backImageName:nil title:@"下一步" titleColor:[UIColor whiteColor]  font:[UIFont systemFontOfSize:17] target:self action:@selector(LandClick)];
    landBtn.backgroundColor = [UIColor colorWithRed:8/255.0 green:65/255.0 blue:130/255.0 alpha:0.8];
    landBtn.layer.cornerRadius = 5.0f;
    
    
    [bgView addSubview:phone2];
    [bgView addSubview:code2];
    [bgView addSubview:userImageView1];
    [bgView addSubview:pwdImageView2];
    [bgView addSubview:line1];
    [self.view addSubview:landBtn];
    
}
#pragma mark 获取验证码和验证码的读取时间
- (void)getValidCode:(UIButton *)sender
{
    
    if ([phone2.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入手机号码"];
        return;
    }
    else if (phone2.text.length <11)
    {
        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
        return;
    }
    //这里加上验证码提示功能
    _oUserPhoneNum = phone2.text;
    //用户交互
    sender.userInteractionEnabled = YES;
    //验证码计时
    self.timeCount = 60;
    //__weak CLForgetPWViewController *weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
    //短信验证功能
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self->phone2.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        if (!error) {
            NSLog(@"成功");
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"验证成功" preferredStyle:UIAlertControllerStyleAlert];
            //            [self presentViewController:alertView animated:YES completion:^{
            [NSThread sleepForTimeInterval:2.0];
            //                [self dismissViewControllerAnimated:YES completion:^{
            //成功之后执行
            //                    [[NSUserDefaults standardUserDefaults] setObject:@"xxxx" forKey:@"nickName"];
            //                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"loginState"];
            //                    [self.navigationController popToRootViewControllerAnimated:YES];
            //                }];
            //            }];
        }else{
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"亲,验证码获取失败,请重新获取"];
            //[SVProgressHUD showError:@"验证码错误" toView:self.navigationController.view];
            
        }
    }];
}
//commit验证短信验证码是否正确
- (void)LandClick{
    
    
    if ([phone2.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入手机号码"];
        return;
    }
    else if (phone2.text.length <11)
    {
        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
        return;
    }
    else if ([code2.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入验证码"];
        return;
    }
    self.keyStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"tel"];
    
    [SMSSDK commitVerificationCode:self->code2.text phoneNumber:phone2.text zone:@"86" result:^(NSError *error) {
        NSLog(@"%@---%@",self->code2.text,self.keyStr);
        if (!error) {
            NSLog(@"成功");
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"验证成功" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alertView animated:YES completion:^{
                [NSThread sleepForTimeInterval:2.0];
                [self dismissViewControllerAnimated:YES completion:^{
#pragma mark 保存手机号和密码值
                                                [[NSUserDefaults standardUserDefaults] setObject:phone2.text forKey:KUserName];
                    //成功之后执行
                    [[NSUserDefaults standardUserDefaults] setObject:@"席小凡" forKey:@"nickName"];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"loginState"];
                    [self.navigationController pushViewController:[[CLNewPWViewController alloc]init] animated:YES];
//[self.navigationController popToRootViewControllerAnimated:YES];
                }];
            }];
        }else{
            NSLog(@"%@",error);
                        [SVProgressHUD showInfoWithStatus:@"亲,您输入的验证码不正确,请重新获取"];
//            [SVProgressHUD showError:@"验证码错误" toView:self.navigationController.view];
        }
    }];
}
//获取验证码
- (void)reduceTime:(NSTimer *)codeTimer {
    self.timeCount--;
    if (self.timeCount == 0) {
        [yyButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [yyButton setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        yyButton.userInteractionEnabled = YES;
        [self.timer invalidate];
    } else {
        NSString *str = [NSString stringWithFormat:@"%lu秒后重新获取", self.timeCount];
        [yyButton setTitle:str forState:UIControlStateNormal];
        yyButton.userInteractionEnabled = NO;
        
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [phone2 resignFirstResponder];
    
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField = [[UITextField alloc]initWithFrame:frame];
    
    textField.font = font;
    
    textField.textColor = [UIColor grayColor];
    
    textField.borderStyle = UITextBorderStyleNone;
    
    textField.placeholder = placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image = [UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor = color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

//验证码完成之后push到新设置密码界面
-(void)landClick
{

        if ([phone2.text isEqualToString:@""])
        {
            [SVProgressHUD showInfoWithStatus:@"亲,请输入注册手机号码"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            return;
        }
        else if (phone2.text.length <11)
        {
            [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });

            return;
        }
        else if ([phone2.text isEqualToString:@""])
        {
            [SVProgressHUD showInfoWithStatus:@"亲,请输入密码"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });

            return;
        }
    
    //获取账户
    NSString *str = [[NSUserDefaults standardUserDefaults] stringForKey:KUserName];
    
    if ([phone2.text isEqualToString:str]) {
        CLNewPWViewController*new=[[CLNewPWViewController alloc]init];
        [self.navigationController pushViewController:new animated:YES];
    }else{
        [SVProgressHUD showErrorWithStatus:@"该账户不存在"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
